package dao

import (
	"driver_srv/basic/config"
	__ "driver_srv/basic/driverproto"
	"driver_srv/handler/models"
	"driver_srv/untils"
	"errors"
	"fmt"

	"regexp"
	"time"
)

/*
CreateDriver 创建司机信息
主要功能:
1. 验证请求参数的必填字段
2. 检查用户信息是否存在且角色正确
3. 检查城市信息是否存在
4. 检查主管信息是否存在
5. 验证身份证号唯一性
6. 解析合同时间(开始时间和结束时间)
7. 创建司机记录
*/
func CreateDriver(in *__.DriverCreateReq, driver *models.Driver) (*__.DriverCreateResp, error) {
	// 检查必填字段
	if in.UserId == 0 || in.CityId == 0 {
		return nil, errors.New("信息不能为空")
	}
	if in.Name == "" || in.IdCard == "" || in.Mobile == "" {
		return nil, errors.New("信息不能为空")
	}
	var user models.User
	user.Id = uint64(in.UserId)
	if err := user.FindUserById(); err != nil {
		return nil, errors.New("用户信息不存在")
	}
	if user.UserRole != 2 {
		return nil, errors.New("用户角色错误,不是司机")
	}

	fmt.Println(user.UserRole)
	var city models.City
	city.Id = in.CityId
	if err := city.FindCityById(); err != nil {
		return nil, errors.New("城市信息不存在")
	}
	if city.City == "" {
		return nil, errors.New("城市信息不存在")
	}
	var manage models.DriverManage
	manage.Id = in.ManagerId
	if err := manage.FindManageName(); err != nil {
		return nil, errors.New("主管信息不存在")
	}
	if manage.Status != 1 {
		return nil, errors.New("司机主管状态错误")
	}
	// 检查身份证号是否已存在
	var count int64
	if err := driver.DriverIdCardUnique(count); err != nil {
		return nil, errors.New("查找身份证失败" + err.Error())
	}
	fmt.Println("count:", count)

	if count > 0 {
		return nil, errors.New("该身份证号已注册")
	}
	// 1. 验证长度，18位
	if len(in.IdCard) != 18 {
		return nil, errors.New("身份证号码长度必须为18位")
	}
	// 2. 验证格式，前17位为数字，最后一位为数字或X
	reg := regexp.MustCompile(`^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$`)
	if !reg.MatchString(in.IdCard) {
		return nil, errors.New("身份证号码格式不正确")
	}
	// 3. 调用腾讯云API进行实名认证
	// 注意：这里保持了对腾讯云封装的调用
	if !untils.RealNames(in.Name, in.IdCard) {
		return nil, errors.New("腾讯云实名认证失败")
	}
	// 手机号验证
	if len(in.Mobile) != 11 {
		return nil, errors.New("手机号长度必须为11位")
	}
	regs := regexp.MustCompile(`^1[3-9]\d{9}$`)
	if !regs.MatchString(in.Mobile) {
		return nil, errors.New("手机号格式错误")
	}
	// 解析合同开始时间
	contractStartTime, err := time.Parse("2006-01-02 15:04:05", in.ContractStartTigme)
	if err != nil {
		contractStartTime = time.Now()
	}
	// 解析合同结束时间
	contractEndTime, err := time.Parse("2006-01-02 15:04:05", in.ContractEndTime)
	if err != nil {
		// 如果合同结束时间解析失败，默认为合同开始时间加一年
		contractEndTime = contractStartTime.AddDate(1, 0, 0)
	}
	driverModel := models.Driver{
		UserId:            uint32(in.UserId),
		CityId:            in.CityId,
		ManageId:          in.ManagerId,
		Name:              in.Name,
		IdCard:            in.IdCard,
		Mobile:            in.Mobile,
		Sex:               uint8(in.Sex),
		Status:            1,
		ContractStartTime: contractStartTime,
		ContractEndTime:   contractEndTime,
	}
	if err = driverModel.DriverCreate(); err != nil {
		return nil, errors.New("创建司机失败")
	}
	return &__.DriverCreateResp{
		User:   driver.Name,
		City:   city.City,
		Manage: "实名认证成功",
	}, nil
}

// UpdateDriver 更新司机信息
func UpdateDriver(in *__.DriverUpdateReq, driver *models.Driver) error {
	// 参数验证
	if in.Id == 0 {
		return errors.New("司机ID不能为空")
	}

	// 开启事务
	tx := config.DB.Begin()
	if tx.Error != nil {
		return fmt.Errorf("开启事务失败: %w", tx.Error)
	}

	// 查找司机信息
	driver.Id = in.Id
	if err := driver.FindDriverById(); err != nil {
		tx.Rollback()
		return fmt.Errorf("司机信息不存在: %w", err)
	}
	DriverLicenseStart, _ := time.Parse("2006-01-02", in.DriverLicenseEnd)
	DriverBirthday, _ := time.Parse("2006-01-02", in.DriverBirthday)
	DriverLicenseEnd, _ := time.Parse("2006-01-02", in.DriverLicenseEnd)
	LicenseIssueDate, _ := time.Parse("2006-01-02", in.LicenseIssueDate)
	FirstLicenseIssueDate, _ := time.Parse("2006-01-02", in.FirstLicenseIssueDate)
	LicenseValidStart, _ := time.Parse("2006-01-02", in.LicenseValidStart)
	LicenseValidEnd, _ := time.Parse("2006-01-02", in.LicenseValidEnd)
	EquipmentDate, _ := time.Parse("2006-01-02", in.EquipmentDate)

	// 字段更新 - 在原有对象基础上更新
	driver.MobileCarriers = 3
	driver.MaritalStatus = uint8(in.MaritalStatus)
	driver.CompanyLogoImg = in.CompanyLogoImg
	driver.RegistrationDistrictCode = in.RegistrationDistrictCode
	driver.Nationality = in.Nationality
	driver.DriverNation = in.DriverNation
	// 驾驶证信息
	driver.DriverLicenseNumber = in.DriverLicenseNumber
	driver.ForeignLanguageAbility = in.ForeignLanguageAbility
	driver.AppVersion = in.AppVersion
	driver.MapType = in.MapType
	driver.Education = in.Education
	driver.DriverLicenseStart = DriverLicenseStart
	driver.DriverLicenseEnd = DriverLicenseEnd
	driver.HouseholdRegistrationAuthority = in.HouseholdRegistrationAuthority
	driver.PermanentAddress = in.PermanentAddress
	driver.CommunicationAddress = in.CommunicationAddress
	driver.DriverPhotoFileNumber = in.DriverPhotoFileNumber
	driver.DriverLicense = in.DriverLicense
	driver.ScanOfMotorVehicleDrivingLicense = in.ScanOfMotorVehicleDrivingLicense
	driver.PermittedVehicleType = in.PermittedVehicleType
	driver.IsTourTaxiDriver = uint8(in.IsTourTaxiDriver)
	driver.OnlineTaxiLicenseNumber = in.OnlineTaxiLicenseNumber
	driver.OnlineTaxiLicenseIssuer = in.OnlineTaxiLicenseIssuer
	driver.IsFullTimeDriver = uint8(in.IsFullTimeDriver)
	driver.IsInBlacklist = uint8(in.IsInBlacklist)
	driver.ServiceType = uint8(in.ServiceType)
	driver.LicenseIssueDate = LicenseIssueDate
	driver.FirstLicenseIssueDate = FirstLicenseIssueDate
	driver.LicenseValidStart = LicenseValidStart
	driver.LicenseValidEnd = LicenseValidEnd
	driver.DriverBirthday = DriverBirthday
	driver.EquipmentDate = EquipmentDate
	driver.ContractSignCompany = in.ContractSignCompany
	driver.EmergencyContact = in.EmergencyContact
	driver.EmergencyContactMobile = in.EmergencyContactMobile
	driver.EmergencyContactAddress = in.EmergencyContactAddress
	driver.UpdatedAt = time.Now()
	// 时间字段处理
	if in.DriverBirthday != "" {
		if birthday, err := time.Parse("2006-01-02", in.DriverBirthday); err == nil {
			driver.DriverBirthday = birthday
		}
	}

	// 执行更新
	if err := driver.DriverMessageByUpdate(tx); err != nil {
		tx.Rollback()
		return fmt.Errorf("更新司机信息失败: %w", err)
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		return fmt.Errorf("提交事务失败: %w", err)
	}

	return nil
}

// 司机与车辆绑定/解绑
func VehicleBind(in *__.VehicleBindReq) error {
	// 1. 校验必填参数
	if in.DriverId == 0 || in.VehicleId == 0 {
		return errors.New("司机ID和车辆ID不能为空")
	}
	if in.BindType != 1 && in.BindType != 2 {
		return errors.New("操作类型无效（1-绑定，2-解绑）")
	}

	// 2. 校验司机是否存在
	var driver models.Driver
	driver.Id = uint32(in.DriverId)
	if err := driver.FindDriverById(); err != nil || driver.Name == "" {
		return errors.New("司机不存在")
	}

	// 3. 校验车辆是否存在
	var vehicle models.Vehicle
	vehicle.Id = uint32(in.VehicleId)
	if err := vehicle.FindVehicleById(); err != nil || vehicle.LicensePlate == "" {
		return errors.New("车辆不存在")
	}

	// 4. 执行绑定/解绑逻辑
	switch in.BindType {
	case 1: // 绑定
		// 检查车辆是否已绑定其他司机
		if vehicle.Bind == 1 && vehicle.DriverId != int32(in.DriverId) {
			return errors.New("该车辆已绑定其他司机")
		}
		// 更新车辆的司机ID和绑定状态
		vehicle.DriverId = int32(in.DriverId)
		vehicle.Bind = 1
	case 2: // 解绑
		// 检查车辆是否已绑定当前司机
		if vehicle.Bind != 1 || vehicle.DriverId != int32(in.DriverId) {
			return errors.New("车辆未绑定当前司机，无法解绑")
		}
		// 清空司机ID，更新绑定状态
		vehicle.DriverId = 0
		vehicle.Bind = 2
	}

	// 5. 保存更新
	vehicle.UpdateAt = time.Now()
	if err := vehicle.UpdateVehicle(); err != nil {
		return errors.New("操作失败：" + err.Error())
	}
	return nil
}

// 创建司机证件图片
func DriverIdImgCreate(in *__.DriverIdImgCreateReq) (*__.DriverIdImgCreateResp, error) {
	var driver models.Driver
	driver.Id = in.DriverId
	if err := driver.FindDriverById(); err != nil {
		return nil, errors.New("司机信息不存在")
	}
	DriverIdImg := models.DriverIdImg{
		DriverId:                             in.DriverId,
		PersonalAvatar:                       in.PersonalAvatar,
		IdCardFront:                          in.IdCardFront,
		IdCardBack:                           in.IdCardBack,
		HeadIdCardBack:                       in.HeadIdCardBack,
		DriverLicenseFrout:                   in.DriverLicenseFrout,
		ProfessionalQualificationCertificate: in.ProfessionalQualificationCertificate,
		Others:                               in.Others,
	}
	if err := DriverIdImg.DriverIdImgCreate(); err != nil {
		return nil, errors.New("创建司机证件图片失败")
	}
	return &__.DriverIdImgCreateResp{
		Id: int64(DriverIdImg.Id),
	}, nil
}

// 创建司机培训课程
func DriverTrainingCourseCreate(in *__.DriverTrainingCourseCreateReq) (*__.DriverTrainingCourseCreateResp, error) {
	var driver models.Driver
	driver.Id = in.DriverId
	if err := driver.FindDriverById(); err != nil {
		return nil, errors.New("司机信息不存在")
	}
	CourseDate, _ := time.Parse("2006-01-02", in.CourseDate)
	StartDate, _ := time.Parse("2006-01-02", in.StartDate)
	EndDate, _ := time.Parse("2006-01-02", in.EndDate)
	driverTrainingCourse := models.DriverTrainingCourse{
		DriverId:   in.DriverId,
		CourseName: in.CourseName,
		CourseDate: CourseDate,
		StartDate:  StartDate,
		EndDate:    EndDate,
		Duration:   in.Duration,
	}
	if err := driverTrainingCourse.DriverTrainingCourseCreate(); err != nil {
		return nil, errors.New("创建司机培训课程失败")
	}
	return &__.DriverTrainingCourseCreateResp{
		Id: int64(driverTrainingCourse.Id),
	}, nil
}

// 创建司机银行账号
func BankAccountCreate(in *__.BankAccountCreateReq) (*__.BankAccountCreateResp, error) {
	var driver models.Driver
	driver.Id = in.DriverId
	if err := driver.FindDriverById(); err != nil {
		return nil, errors.New("司机信息不存在")
	}
	bankAccount := models.BankAccount{
		DriverId:       in.DriverId,
		BankName:       in.BankName,
		BankCardNumber: in.BankCardNumber,
	}
	if err := bankAccount.BankAccountCreate(); err != nil {
		return nil, errors.New("创建司机银行账号失败")
	}
	return &__.BankAccountCreateResp{
		Id: int64(bankAccount.Id),
	}, nil
}

// DriverList 司机详情列表查询
func DriverList(in *__.DriverListReq) (*__.DriverListResp, error) {
	// 调用model层方法查询司机列表
	var driverss models.Driver
	driverss.Id = uint32(in.DriverId)
	drivers, total, err := driverss.FindDriverList(in.DriverId, int(in.Page), int(in.PageSize))
	if err != nil {
		return nil, errors.New("查询司机列表失败：" + err.Error())
	}
	// 准备响应
	resp := &__.DriverListResp{
		Total: total,
		Items: []*__.DriverListItem{},
	}

	// 遍历司机，获取关联数据
	for _, driver := range drivers {
		// 创建列表项
		item := &__.DriverListItem{
			Id:                               int64(driver.Id),
			UserId:                           int64(driver.UserId),
			CityId:                           driver.CityId,
			ManagerId:                        driver.ManageId,
			Name:                             driver.Name,
			IdCard:                           driver.IdCard,
			Mobile:                           driver.Mobile,
			Sex:                              uint32(driver.Sex),
			ContractStartTime:                driver.DriverNation,
			ContractEndTime:                  driver.DriverLicense,
			MobileCarriers:                   int64(driver.MobileCarriers),
			CompanyLogoImg:                   driver.CompanyLogoImg,
			RegistrationDistrictCode:         driver.RegistrationDistrictCode,
			DriverBirthday:                   driver.DriverBirthday.Format("2006-01-02"),
			Nationality:                      driver.Nationality,
			DriverNation:                     driver.DriverNation,
			DriverLicenseNumber:              driver.DriverLicenseNumber,
			MaritalStatus:                    int64(driver.MaritalStatus),
			ForeignLanguageAbility:           driver.ForeignLanguageAbility,
			AppVersion:                       driver.AppVersion,
			MapType:                          driver.MapType,
			Education:                        driver.Education,
			HouseholdRegistrationAuthority:   driver.HouseholdRegistrationAuthority,
			PermanentAddress:                 driver.PermanentAddress,
			CommunicationAddress:             driver.CommunicationAddress,
			DriverPhotoFileNumber:            driver.DriverPhotoFileNumber,
			DriverLicense:                    driver.DriverLicense,
			ScanOfMotorVehicleDrivingLicense: driver.ScanOfMotorVehicleDrivingLicense,
			PermittedVehicleType:             driver.PermittedVehicleType,
			DriverLicenseStart:               driver.DriverLicenseStart.Format("2006-01-02"),
			DriverLicenseEnd:                 driver.DriverLicenseEnd.Format("2006-01-02"),
			IsTourTaxiDriver:                 int64(driver.IsTourTaxiDriver),
			OnlineTaxiLicenseNumber:          driver.OnlineTaxiLicenseNumber,
			OnlineTaxiLicenseIssuer:          driver.OnlineTaxiLicenseIssuer,
			LicenseIssueDate:                 driver.DriverLicenseNumber,
			FirstLicenseIssueDate:            driver.FirstLicenseIssueDate.Format("2006-01-02"),
			LicenseValidStart:                driver.DriverLicenseStart.Format("2006-01-02"),
			LicenseValidEnd:                  driver.DriverLicenseEnd.Format("2006-01-02"),
			EquipmentDate:                    driver.EquipmentDate.Format("2006-01-02"),
			IsFullTimeDriver:                 int64(driver.IsFullTimeDriver),
			IsInBlacklist:                    int64(driver.IsInBlacklist),
			ServiceType:                      int64(driver.ServiceType),
			ContractSignCompany:              driver.ContractSignCompany,
			EmergencyContact:                 driver.EmergencyContact,
			EmergencyContactMobile:           driver.EmergencyContactMobile,
			EmergencyContactAddress:          driver.EmergencyContactAddress,
			TrainingCourses:                  []*__.TrainingCourseInfo{},
			BankAccount:                      &__.BankAccountInfo{},
			VehicleInfo:                      &__.VehicleInfos{},
			IdImgs:                           &__.DriverIdImgInfo{},
		}
		// 使用model层方法获取所有关联数据
		vehicle, trainingCourses, bankAccount, idImg, err := driver.GetAllRelatedData()
		if err != nil {
			return nil, errors.New("获取司机关联数据失败：" + err.Error())
		}
		// 填充车辆信息
		if vehicle != nil {
			item.VehicleInfo = &__.VehicleInfos{
				LicensePlate: vehicle.LicensePlate,
				Description:  fmt.Sprintf("车牌号：%s", vehicle.LicensePlate), // 简单描述
			}
		}
		// 填充培训课程信息
		if len(trainingCourses) > 0 {
			item.TrainingCourses = []*__.TrainingCourseInfo{}
			for _, course := range trainingCourses {
				item.TrainingCourses = append(item.TrainingCourses, &__.TrainingCourseInfo{
					CourseName: course.CourseName,
					CourseDate: course.CourseDate.Format("2006-01-02"),
				})
			}
		}
		// 填充银行账户信息
		if bankAccount != nil {
			item.BankAccount = &__.BankAccountInfo{
				BankName:       bankAccount.BankName,
				BankCardNumber: bankAccount.BankCardNumber,
			}
		}
		// 填充证件图片信息
		if idImg != nil {
			item.IdImgs = &__.DriverIdImgInfo{
				PersonalAvatar:     idImg.PersonalAvatar,
				IdCardFront:        idImg.IdCardFront,
				IdCardBack:         idImg.IdCardBack,
				HeadIdCardBack:     idImg.HeadIdCardBack,
				DriverLicenseFrout: idImg.DriverLicenseFrout,
			}
		}
		// 添加到响应
		resp.Items = append(resp.Items, item)
	}

	return resp, nil
}

// DriverList 司机详情列表查询
func DriverLists(in *__.DriverListsReq) (*__.DriverListsResp, error) {
	// 调用model层方法查询司机列表
	var driverss models.Driver
	driver, i, err := driverss.ListsDriver(int(in.Page), int(in.PageSize))
	if err != nil {
		return nil, errors.New("查询司机列表失败：" + err.Error())
	}
	// 准备响应
	resp := &__.DriverListsResp{
		Total: i,
		List:  []*__.DriverList{},
	}

	// 遍历司机，获取关联数据
	for _, driver := range driver {
		// 创建列表项
		list := &__.DriverList{
			Id:                               int64(driver.Id),
			UserId:                           int64(driver.UserId),
			CityId:                           driver.CityId,
			ManagerId:                        driver.ManageId,
			Name:                             driver.Name,
			IdCard:                           driver.IdCard,
			Mobile:                           driver.Mobile,
			Sex:                              uint32(driver.Sex),
			ContractStartTime:                driver.DriverNation,
			ContractEndTime:                  driver.DriverLicense,
			MobileCarriers:                   int64(driver.MobileCarriers),
			CompanyLogoImg:                   driver.CompanyLogoImg,
			RegistrationDistrictCode:         driver.RegistrationDistrictCode,
			DriverBirthday:                   driver.DriverBirthday.Format("2006-01-02"),
			Nationality:                      driver.Nationality,
			DriverNation:                     driver.DriverNation,
			DriverLicenseNumber:              driver.DriverLicenseNumber,
			MaritalStatus:                    int64(driver.MaritalStatus),
			ForeignLanguageAbility:           driver.ForeignLanguageAbility,
			AppVersion:                       driver.AppVersion,
			MapType:                          driver.MapType,
			Education:                        driver.Education,
			HouseholdRegistrationAuthority:   driver.HouseholdRegistrationAuthority,
			PermanentAddress:                 driver.PermanentAddress,
			CommunicationAddress:             driver.CommunicationAddress,
			DriverPhotoFileNumber:            driver.DriverPhotoFileNumber,
			DriverLicense:                    driver.DriverLicense,
			ScanOfMotorVehicleDrivingLicense: driver.ScanOfMotorVehicleDrivingLicense,
			PermittedVehicleType:             driver.PermittedVehicleType,
			DriverLicenseStart:               driver.DriverLicenseStart.Format("2006-01-02"),
			DriverLicenseEnd:                 driver.DriverLicenseEnd.Format("2006-01-02"),
			IsTourTaxiDriver:                 int64(driver.IsTourTaxiDriver),
			OnlineTaxiLicenseNumber:          driver.OnlineTaxiLicenseNumber,
			OnlineTaxiLicenseIssuer:          driver.OnlineTaxiLicenseIssuer,
			LicenseIssueDate:                 driver.DriverLicenseNumber,
			FirstLicenseIssueDate:            driver.FirstLicenseIssueDate.Format("2006-01-02"),
			LicenseValidStart:                driver.DriverLicenseStart.Format("2006-01-02"),
			LicenseValidEnd:                  driver.DriverLicenseEnd.Format("2006-01-02"),
			EquipmentDate:                    driver.EquipmentDate.Format("2006-01-02"),
			IsFullTimeDriver:                 int64(driver.IsFullTimeDriver),
			IsInBlacklist:                    int64(driver.IsInBlacklist),
			ServiceType:                      int64(driver.ServiceType),
			ContractSignCompany:              driver.ContractSignCompany,
			EmergencyContact:                 driver.EmergencyContact,
			EmergencyContactMobile:           driver.EmergencyContactMobile,
			EmergencyContactAddress:          driver.EmergencyContactAddress,
			TrainingCourses:                  []*__.TrainingCourseInfo{},
			BankAccount:                      &__.BankAccountInfo{},
			VehicleInfo:                      &__.VehicleInfos{},
			IdImgs:                           &__.DriverIdImgInfo{},
		}
		// 使用model层方法获取所有关联数据
		vehicle, trainingCourses, bankAccount, idImg, err := driver.GetAllRelatedData()
		if err != nil {
			return nil, errors.New("获取司机关联数据失败：" + err.Error())
		}
		// 填充车辆信息
		if vehicle != nil {
			list.VehicleInfo = &__.VehicleInfos{
				LicensePlate: vehicle.LicensePlate,
				Description:  fmt.Sprintf("车牌号：%s", vehicle.LicensePlate), // 简单描述
			}
		}
		// 填充培训课程信息
		if len(trainingCourses) > 0 {
			list.TrainingCourses = []*__.TrainingCourseInfo{}
			for _, course := range trainingCourses {
				list.TrainingCourses = append(list.TrainingCourses, &__.TrainingCourseInfo{
					CourseName: course.CourseName,
					CourseDate: course.CourseDate.Format("2006-01-02"),
				})
			}
		}
		// 填充银行账户信息
		if bankAccount != nil {
			list.BankAccount = &__.BankAccountInfo{
				BankName:       bankAccount.BankName,
				BankCardNumber: bankAccount.BankCardNumber,
			}
		}
		// 填充证件图片信息
		if idImg != nil {
			list.IdImgs = &__.DriverIdImgInfo{
				PersonalAvatar:     idImg.PersonalAvatar,
				IdCardFront:        idImg.IdCardFront,
				IdCardBack:         idImg.IdCardBack,
				HeadIdCardBack:     idImg.HeadIdCardBack,
				DriverLicenseFrout: idImg.DriverLicenseFrout,
			}
		}
		// 添加到响应
		resp.List = append(resp.List, list)
	}

	return resp, nil
}

// 查询司机营业额
func DriverRevenue(in *__.DriverRevenueReq) (*__.DriverRevenueResp, error) {
	// 1. 验证司机是否存在
	var driver models.Driver
	driver.Id = uint32(in.DriverId)
	if err := driver.FindDriverById(); err != nil {
		return nil, errors.New("司机信息不存在")
	}

	// 2. 验证参数
	if in.StartDate == "" || in.EndDate == "" {
		return nil, errors.New("开始日期和结束日期不能为空")
	}
	if in.Type != 1 && in.Type != 2 {
		return nil, errors.New("统计类型只能是1（日统计）或2（月统计）")
	}

	// 3. 查询营业额列表
	var revenueModel models.DriverRevenue
	list, err := revenueModel.FindListByDriverAndTimeRange(
		uint32(in.DriverId),
		in.StartDate,
		in.EndDate,
		int8(in.Type),
	)
	if err != nil {
		return nil, errors.New("查询营业额失败：" + err.Error())
	}

	// 4. 计算总营业额
	var totalRevenue float64
	var revenueItems []*__.RevenueItem
	for _, item := range list {
		totalRevenue += item.TotalRevenue
		revenueItems = append(revenueItems, &__.RevenueItem{
			Date:         item.Date,
			OrderCount:   int32(item.OrderCount),
			TotalRevenue: float64(item.TotalRevenue),
		})
	}

	// 5. 构造响应
	return &__.DriverRevenueResp{
		DriverId:    in.DriverId,
		DriverName:  driver.Name,
		RevenueList: revenueItems,
		Total:       totalRevenue,
	}, nil
}
